const express = require('express');
const router = express.Router();
const { Log } = require('../../models');
const { Op, where } = require('sequelize');
const { NotFound } = require('http-errors');
const { success, failure } = require('../../utils/responses');
const { getKeysByPattern, delKey, getKey, setKey } = require('../../utils/redis');

/**
 * 公共方法: 查询当前文章
 * */

async function getLogs(req) {
  const { id } = req.params;
  const log = await Log.findByPk(id);
  if (!log) {
    throw new NotFound(`ID: ${id}的日志没找到`);
  }
  return log;
}

/**
 * 查询日志列表
 * */
router.get('/', async function (req, res) {
  try {
    const query = req.query;
    // 当前第几页，如果不传默认第一页
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    // 当前多少条数据，如果不传默认10条数据
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    // 计算offset
    const offset = (currentPage - 1) * pageSize;

    const condition = {
      where: {},
      order: [['id', 'DESC']],
      limit: pageSize,
      offset,
    };

    const { count: total, rows } = await Log.findAndCountAll(condition);

    success(res, '查询成功', {
      logs: rows,
      pagination: {
        total,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询日志详情
 * */
router.get('/:id', async function (req, res) {
  try {
    const logs = await getLogs(req);
    success(res, '查询成功', { logs });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除日志
 * */
router.delete('/:id', async function (req, res) {
  try {
    const log = await getLogs(req);
    await log.destroy();
    success(res, '删除成功');
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
